# coding: utf-8
from datetime import datetime

import web

from libs import utils
from libs.utils import render, require_captcha, show_error, db, set_self_user


class register:
    @set_self_user
    def GET(self):

        return render("login/register", action=self)

    @require_captcha
    def POST(self):
        post = web.input()
        username = post.username
        password = post.password
        password_confirm = post.password_confirm

        if password != password_confirm:
            return show_error('两次密码必须相等')

        salt = utils.generate_random_str(10)
        time_str = utils.format_time1(datetime.now())
        password_db = utils.sha1(password + salt + time_str)

        user_count = db.query("select count(*) as total from user where username=$username", vars={'username': username})[0].total
        if user_count:
            return show_error('用户名已经存在')

        user_id = db.insert('user', username=username, password=password_db, salt=salt, create_time=time_str)

        web.ctx.session['user_id'] = user_id

        return web.seeother('/')


class login:
    @set_self_user
    def GET(self):

        return render('login/login', action=self)

    @require_captcha
    def POST(self):
        post = web.input()
        username = post.username
        password = post.password

        try:
            user = db.select('user', where={'username': username})[0]
            password_db = user.password
            salt = user.salt
            create_time = utils.format_time1(user.create_time)

            assert password_db == utils.sha1(password + salt + create_time)

            web.ctx.session['user_id'] = user.id
            return web.seeother('/')
        except Exception as e:
            return show_error('用户不存在或密码错误')


class logout:
    def GET(self):
        web.ctx.session['user_id'] = ''

        return web.seeother('/')
